﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyApp.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthoizeController : ControllerBase
    {
        /// <summary>
        /// 输入名字登录
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public string Login(string username)
        {
            if (!string.IsNullOrEmpty(username))
            {
                //登陆成功
                var claims = new Claim[]
                    {
                new Claim(ClaimTypes.Name, "client"),
                new Claim("Id","0001"),
                new Claim("UserName", username)
                        //不能放敏感信息 
                    };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yuanfengchao2022"));
                //issuer代表颁发Token的Web应用程序，audience是Token的受理者
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:6060",
                    audience: "http://localhost:5000",
                    claims: claims,
                    notBefore: DateTime.Now,
                    expires: DateTime.Now.AddHours(1),
                    signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
                var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return "Bearer " + jwtToken;
            }
            else
            {
                return "账号或密码错误";
            }
        }

        /// <summary>
        /// 默认登录
        /// </summary>
        /// <returns></returns>
        [HttpGet("LoginTest")]
        public string LoginTest()
        {
            var claims = new Claim[]
                {
                new Claim(ClaimTypes.Name, "client"),
                new Claim("Id","0001"),
                new Claim("UserName", "张三")
                    //不能放敏感信息 
                };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yuanfengchao2022"));
            //issuer代表颁发Token的Web应用程序，audience是Token的受理者
            var token = new JwtSecurityToken(
                issuer: "http://localhost:6060",
                audience: "http://localhost:5000",
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddHours(1),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            return "Bearer " + jwtToken;

        }
    }
}
